<?php
/**
* order.php
*/
session_start();
include_once("config/config.inc.php");
include_once("paymentpad.php");
include_once("reporting.php");
include_once("currentcash.function.php");

/**(
* ajax part
*/

$user = $_SESSION["hotel"]["userid"];

if($_GET["roomid"]) { //run on page load to get occupancy id
	$room = $_GET["roomid"];
	$sql = " select a.occupancy_id, a.actual_checkin, b.door_name, c.rate_name, a.shift_checkin, d.fullname
			from occupancy a, rooms b, rates c, users d
			where a.room_id=b.room_id and a.rate_id=c.rate_id and a.update_by=d.user_id and a.room_id=$room and actual_checkout='0000-00-00 00:00:00' ";
	$res = mysql_query($sql);
	list($occupancy, $checkindate,$doorname,$ratename,$shift,$fullname)=mysql_fetch_row($res);
}

if($_POST["act"]=="add") {
	$occupancy=$_POST["occupancy"];
	$showpayment = $_POST["showpayment"];
	$order_code = $_POST["order_code"] ? $_POST["order_code"] : mktime();
	parse_str($_POST["data"]);
	
	list($categfrom, $thiscateg)=explode("_", $newsascateg);
	if($categfrom == 'm') {
		$table = "room_sales";
		$thisitem  =  $newsasitem;
	}elseif($categfrom == 'f') {
		$table = "fnb_sales";
		$thisitem = $newfooditem;
	}
	$now = date("Y-m-d H:i:s");
	//$thiscateg = getcategoryfromitem($newsascateg, $thisitem);
	
	$sql = "select fnb_id from fnb where food_category_id ='$thiscateg'  and fnb_id = '$thisitem'";
	$res = mysql_query($sql) or die(mysql_error().$sql);
	$num = mysql_num_rows($res);
	
	
	$sql = "select * from `sales_and_services` where sas_cat_id = '$thiscateg' and sas_id = '$thisitem'";
	$res = mysql_query($sql) or die(mysql_error().$sql);
	$num2 = mysql_num_rows($res);

	$num = $num2 + $num;

	if($num > 0)
	{
		$sql = "insert into $table (sales_date, order_code, occupancy_id, category_id, item_id,  unit_cost, qty, update_by ,remarks )
					values ('$now', '$order_code', '$occupancy', '$thiscateg' ,'$thisitem', '$newunitprice' ,'$qty' ,'$user','$newremarks');
			";
		mysql_query($sql) or die($sql . mysql_error()) ; // save t this transaction
	}
	echo gettransactions( $occupancy, $order_code,$showpayment) ;
	//echo gettransactions(4, $occupancy) ;
	exit; //do not continue execution of rest of the script
}elseif($_POST["act"]=="viewoc") {
	$occupancy=$_POST["occupancy"];
	$showpayment = $_POST["showpayment"];
	$order_code = $_POST["order_code"] ? $_POST["order_code"] : mktime();
	parse_str($_POST["data"]);
	echo gettransactions( $occupancy, $order_code, $showpayment) ;
	exit;
}elseif($_POST["act"]=="cmd") {
	parse_str($_POST["data"]);
	$newstatus = $_POST["newstatus"];
	$showpayment = $_POST["showpayment"];
	
	$now = date("Y-m-d H:i:s");
	if($newstatus=='Remove') {
		$thisstat = 'Removed';
		if(is_array($cb_1) ) {
			$sas = implode(',', $cb_1);
			$sql = "delete from room_sales where roomsales_id in ($sas) ";
			mysql_query($sql);
		}
		if(is_array($cb_4) ) {
			$fnb = implode(',',$cb_4);
			$sql = "delete from fnb_sales  where fnbsales_id in ($fnb) ";
			mysql_query($sql);
		}
	}elseif($newstatus=='Pay'){
		//die($newchange.",,,,,,,,".$new_alreadypayed);
		$_sql = "select * from fnb_sales where order_code = '$order_code' and status in ('Paid')";
		$_res = mysql_query($_sql);
		$_num = mysql_num_rows($_res);
		/*
		* get only the items selected
		*/
		if(is_array($cb_4)) {
			$selected = implode(',' , $cb_4 );
		} else {
			$selected = $cb_4;
		}
		$now = date("Y-m-d H:i:s");
		if($_num <= 0)
		{
			$thisstat = "Paid";
			$sql = "update room_sales set status='$thisstat',update_by='$user',update_date = '$now' where status<>'Cancelled' and order_code = $order_code ";
			/*
			$sql = "update room_sales set status='$thisstat',update_by='$user',update_date = '$now' where status<>'Cancelled' and order_code = $order_code 
				and roomsales_id in ($selected)
			";*/
			mysql_query($sql);
			$sql = "update fnb_sales set status='$thisstat',update_by='$user',update_date = '$now' where status<>'Cancelled' and  order_code = $order_code ";
			/*
			$sql = "update fnb_sales set status='$thisstat',update_by='$user',update_date = '$now' where status<>'Cancelled' and  order_code = $order_code 
				and fnbsales_id in ($selected)
			";*/
			mysql_query($sql);
			/* salesreciepts*/
			//cash
			if($newcash > 0) {
				$tendered = $newcash - $newchange;
				$sql = " insert into salesreceipts(receipt_date, occupancy_id, tendertype, amount,reference_id,update_by) 
					values ('$now', '$occupancy', 'Cash', '$tendered','$order_code','$user')";
				mysql_query($sql) or die(mysql_error());
				setCurrentCash($tendered,'in',$_SESSION["hotel"]["userid"]);		
				//banquet
				if($newfooditem==115 && $newsascateg=='f_23') {
					if(is_array($cb_4)) {
						$fnb = ' and fnbsales_id in (' . implode(',',$cb_4) . ')' ;
					}
					$sql  = "update fnb_sales set unit_cost='$newcash' where order_code='$order_code' $fnb ";
					mysql_query($sql) or die(mysql_error() . $sql);
					
				}
				
				//misc adjustment
				if($newsasitem==29 && $newsascateg=='m_1') {
					if(is_array($cb_4)) {
						$fnb = ' and roomsales_id in (' . implode(',',$cb_4) . ')' ;
					}
					$sql  = "update room_sales set unit_cost='$newcash' where order_code='$order_code' $fnb ";
					mysql_query($sql) or die(mysql_error() . $sql);
					
				}
			}

			if($new_alreadypayed != '1')
			{
				if($newchange > 0 || $newchange != "") {
				$sql = " insert into salesreceipts(receipt_date, occupancy_id, tendertype, amount, reference_id,update_by) 
					values ('$now', '$occupancy', 'Deposit', '$newchange','$order_code','$user')";
				mysql_query($sql) or die(mysql_error());
				setCurrentCash($newchange,'in',$_SESSION["hotel"]["userid"]);
				}
			}
		//card
			if($newcard > 0) {				
				$sql = " insert into salesreceipts(receipt_date, occupancy_id, tendertype, amount,reference_id,update_by) 
						values ('$now', '$occupancy', 'Card', '$newcard','$order_code','$user')";
				mysql_query($sql) or die(mysql_error());
				//insert card details
				$newsalesid = mysql_insert_id();
				$sql = " insert into card_payment_details (salesreceipt_id, cardtype, approval_code, batch_number) 
							values ('$newsalesid','$ctype','$newapproval','$newbatch')";
				mysql_query($sql) or die(mysql_error());
				//banquet
				if($newfooditem==115 && $newsascateg=='f_23') {
					if(is_array($cb_4)) {
						$fnb = ' and fnbsales_id in (' . implode(',',$cb_4) . ')' ;
					}
					$sql  = "update fnb_sales set unit_cost='$newcard' where order_code='$order_code' $fnb ";
					mysql_query($sql) or die(mysql_error() . $sql);
					
				}
				//misc adjustment
				if($newsasitem==29 && $newsascateg=='m_1') {
					if(is_array($cb_4)) {
						$fnb = ' and roomsales_id in (' . implode(',',$cb_4) . ')' ;
					}
					$sql  = "update room_sales set unit_cost='$newcard' where order_code='$order_code' $fnb ";
					mysql_query($sql) or die(mysql_error() . $sql);
					
				}
			}
		}
	}elseif($newstatus=='Print'){
		$obj = new Reporting($roomid);
		$thisstat = 'Printed';
		$sql = "update room_sales set status='$thisstat',update_by='$user',update_date = '".date("Y-m-d H:i:s")."' where order_code = $order_code and status <> 'Cancelled'";
		mysql_query($sql);
		if(mysql_affected_rows()) {
			$_sql = "select unit_cost*qty,category_id from room_sales where order_code = '$order_code'";
			$_res = mysql_query($_sql);
			list($cost,$category_id)=mysql_fetch_row($_res);

			if($cost=="0.00"||!$cost)
			{
				$p = 2;
			}else{
				$p = 3;
			}
			
						
			
			if($category_id==4)
			{
				//other services				
				$retval=chr(hexdec('1B')).chr(hexdec('4D')).chr(1);
				$retval.=$obj->printablemos(1,$order_code)."\n\n\n\n\n";
				$retval.=chr(hexdec('1D')).chr(hexdec('56')).chr(49);								
				$file = "mos{$room}.txt";
				$fp = fopen("reports/" .$file, "w");
				fwrite( $fp,$retval);
				fclose($fp);
				//die("xx");
				shell_exec('c:\pstools\psexec c:\xampp\htdocs\fds\ajax\p.bat ' . $file);
			}
			else
			{

				//miscellaneous
				$retval=chr(hexdec('1B')).chr(hexdec('4D')).chr(1);
				$retval.=$obj->printablemos(1,$order_code)."\n\n\n\n\n";
				$retval.=chr(hexdec('1D')).chr(hexdec('56')).chr(49);
				$retval.=$obj->printablemos(1,$order_code)."\n\n\n\n\n";
				$retval.=chr(hexdec('1D')).chr(hexdec('56')).chr(49);
			
				if($p == 3)
				{
					$retval.=$obj->printablemos(1,$order_code)."\n\n\n\n\n";
					$retval.=chr(hexdec('1D')).chr(hexdec('56')).chr(49);								
				}
				$file = "mos{$room}.txt";
				$fp = fopen("reports/" .$file, "w");
				fwrite( $fp,$retval);
				fclose($fp);
				
				shell_exec('c:\pstools\psexec c:\xampp\htdocs\fds\ajax\p_kitchen.bat ' . $file);
			}
		}
		$sql = "update fnb_sales set status='$thisstat',update_by='$user',update_date = '".date("Y-m-d H:i:s")."' where order_code = $order_code and status <> 'Cancelled'";
		mysql_query($sql);
		if(mysql_affected_rows()) {
			$_sql = "select unit_cost*qty from fnb_sales where order_code = '$order_code'";
			$_res = mysql_query($_sql);
			list($cost)=mysql_fetch_row($_res);

			if($cost=="0.00"||!$cost)
			{
				$p = 2;
			}else{
				$p = 3;
			}
			$retval=chr(hexdec('1B')).chr(hexdec('4D')).chr(1);
			$retval.=$obj->printablefos(1,$order_code)."\n\n\n\n\n";
			$retval.=chr(hexdec('1D')).chr(hexdec('56')).chr(49);
			$retval.=$obj->printablefos(1,$order_code)."\n\n\n\n\n";
			$retval.=chr(hexdec('1D')).chr(hexdec('56')).chr(49);

			if($p == 3)
			{
				$retval.=$obj->printablefos(1,$order_code)."\n\n\n\n\n";
				$retval.=chr(hexdec('1D')).chr(hexdec('56')).chr(49);								
			}

			$file = "fos{$room}.txt";
			$fp = fopen("reports/" .$file, "w");
			fwrite( $fp,$retval);
			fclose($fp);	
			
			shell_exec('c:\pstools\psexec c:\xampp\htdocs\fds\ajax\p_kitchen.bat ' . $file);				
			
		}

	}elseif($newstatus=='RePrint'){
		$obj = new Reporting($roomid);
		$thisstat = 'Printed';
		$sql = "update room_sales set status='$thisstat',update_by='$user',update_date = '".date("Y-m-d H:i:s")."' where order_code = $order_code and status <> 'Cancelled'";
		mysql_query($sql);
		if(mysql_affected_rows()) {
			$_sql = "select unit_cost*qty from fnb_sales where order_code = '$order_code'";
			$_res = mysql_query($_sql);
			list($cost)=mysql_fetch_row($_res);

			if($cost=="0.00"||!$cost)
			{
				$p = 2;
			}else{
				$p = 3;
			}
			$retval=chr(hexdec('1B')).chr(hexdec('4D')).chr(1);
			$retval.=$obj->printablemos(1,$order_code)."\n\n\n\n\n";
			$retval.=chr(hexdec('1D')).chr(hexdec('56')).chr(49);
			$retval.=$obj->printablemos(1,$order_code)."\n\n\n\n\n";
			$retval.=chr(hexdec('1D')).chr(hexdec('56')).chr(49);
			
			if($p == 3)
			{
				$retval.=$obj->printablemos(1,$order_code)."\n\n\n\n\n";
				$retval.=chr(hexdec('1D')).chr(hexdec('56')).chr(49);								
			}
						
			$file = "mos{$room}.txt";
			$fp = fopen("reports/" .$file, "w");
			fwrite( $fp,$retval);
			fclose($fp);

			
			shell_exec('c:\pstools\psexec c:\xampp\htdocs\fds\ajax\p_kitchen.bat ' . $file);			 
		}
		$sql = "update fnb_sales set status='$thisstat',update_by='$user',update_date = '".date("Y-m-d H:i:s")."' where order_code = $order_code and status <> 'Cancelled'";
		mysql_query($sql);
		if(mysql_affected_rows()) {
			$_sql = "select unit_cost*qty from fnb_sales where order_code = '$order_code'";
			$_res = mysql_query($_sql);
			list($cost)=mysql_fetch_row($_res);

			if($cost=="0.00"||!$cost)
			{
				$p = 2;
			}else{
				$p = 3;
			}
			$retval=chr(hexdec('1B')).chr(hexdec('4D')).chr(1);
			$retval.=$obj->printablefos(1,$order_code)."\n\n\n\n\n";
			$retval.=chr(hexdec('1D')).chr(hexdec('56')).chr(49);
			$retval.=$obj->printablefos(1,$order_code)."\n\n\n\n\n";
			$retval.=chr(hexdec('1D')).chr(hexdec('56')).chr(49);

			if($p == 3)
			{
				$retval.=$obj->printablefos(1,$order_code)."\n\n\n\n\n";
				$retval.=chr(hexdec('1D')).chr(hexdec('56')).chr(49);								
			}

			$file = "fos{$room}.txt";
			$fp = fopen("reports/" .$file, "w");
			fwrite( $fp,$retval);
			fclose($fp);	
			
			shell_exec('c:\pstools\psexec c:\xampp\htdocs\fds\ajax\p_kitchen.bat ' . $file);			
		}
	}
	elseif($newstatus=='Cancel'){
		$obj = new Reporting($roomid);
		$thisstat = 'Cancelled';
		if(is_array($cb_1) ) {
			$sas = implode(',', $cb_1);
			$sql = "update room_sales set status='$thisstat',update_by='$user',update_date = '".date("Y-m-d H:i:s")."' where roomsales_id in ($sas) ";
			mysql_query($sql);
			//start printing
			$retval=chr(hexdec('1B')).chr(hexdec('4D')).chr(1);
			$output = $obj->printablemoscancel($sas)."\n\n\n\n\n";
			for($p=0; $p < 2; $p++) 
			{
				$retval.= $output;
				$retval.=chr(hexdec('1D')).chr(hexdec('56')).chr(49);								
			}
			$file = "moscancel{$room}.txt";
			$fp = fopen("reports/" .$file, "w");
			fwrite( $fp,$retval);
			fclose($fp);	
			shell_exec('c:\pstools\psexec c:\xampp\htdocs\fds\ajax\p_kitchen.bat ' . $file);
			shell_exec('c:\pstools\psexec c:\xampp\htdocs\fds\ajax\p.bat ' . $file);
		
		}
		if(is_array($cb_4) ) {
				$fnb = implode(',',$cb_4);
				$sql = "update fnb_sales set status='$thisstat',update_by='$user',update_date = '".date("Y-m-d H:i:s")."' where fnbsales_id in ($fnb) ";
				mysql_query($sql);
			//start printing
			$retval=chr(hexdec('1B')).chr(hexdec('4D')).chr(1);
			$output = $obj->printablefoscancel($fnb)."\n\n\n\n\n";
			for($p=0; $p < 2; $p++) 
			{
				$retval.= $output;
				$retval.=chr(hexdec('1D')).chr(hexdec('56')).chr(49);								
			}
			$file = "foscancel{$room}.txt";
			$fp = fopen("reports/" .$file, "w");
			fwrite( $fp,$retval);
			fclose($fp);	
			shell_exec('c:\pstools\psexec c:\xampp\htdocs\fds\ajax\p_kitchen.bat ' . $file);
			shell_exec('c:\pstools\psexec c:\xampp\htdocs\fds\ajax\p.bat ' . $file);
		
		}

	}
	if(is_array($cb_1) ) {
		$sas = implode(',', $cb_1);
		$sql = "update room_sales set status='$thisstat',update_by='$user',update_date = '".date("Y-m-d H:i:s")."' where roomsales_id in ($sas) ";
		mysql_query($sql);
	}
	if(is_array($cb_4) ) {
		$fnb = implode(',',$cb_4);
		$sql = "update fnb_sales set status='$thisstat',update_by='$user',update_date = '".date("Y-m-d H:i:s")."' where fnbsales_id in ($fnb) ";
		mysql_query($sql);
	}
	
	echo gettransactions( $occupancy, $order_code, $showpayment) ;
	exit;
}

function gettransactions( $occupancy, $order_code='', $showpayment=0) {
	$typearr = array(1, 4);
	$retval = "";
	$grandtotal = 0;
	$laststatus="";
	foreach($typearr as $type) {
	if($type==1) {
	// extract from room_sales
		$sql = " select  a.roomsales_id, a.sales_date, b.sas_cat_name, c.sas_description, a.unit_cost, a.qty ,a.status
				from room_sales  a, sas_category b, sales_and_services c
				where a.item_id=c.sas_id and b.sas_cat_id=c.sas_cat_id  and a.occupancy_id='$occupancy' and a.status not in ('Cancelled') and a.order_code='$order_code'
				and b.sas_cat_id <> 3
				order by b.sas_cat_name, a.sales_date 
				";
		$typeheader = "Miscellaneous";
	}elseif($type==4) {
		$sql = " select  a.fnbsales_id, a.sales_date, b.food_category_name, c.fnb_name, a.unit_cost, a.qty ,a.status
				from fnb_sales  a, food_categories b, fnb c
				where a.item_id=c.fnb_id and a.category_id=c.food_category_id and b.food_category_id=c.food_category_id and a.occupancy_id='$occupancy'
				and a.order_code='$order_code' and a.status not in ( 'Cancelled' )
				order by a.sales_date 
				";
		$typeheader = "Food & Beverages";
	}
	$cbname = "cb_$type" . '[]';
	$res = mysql_query($sql) or die($sql. mysql_error());
	
	
	if(mysql_num_rows($res)) {
		$oldcateg = "";
		$total = 0;
	
		$retval .= "<tr><td colspan=6 class='hdr-heading'>$typeheader</td></tr>";
		
		while(list($sid, $date,$catname,$itemname,$unitcost, $qty,$status) = mysql_fetch_row($res)) {
			if($oldcateg != $catname) {
				$retval .= "<tr><td colspan=6 class='subhdr'>$catname</td></tr>";
			}
			$retval .= "<tr>";
			if($status!='Paid') {
				$retval .= "<td><input type='checkbox' name='$cbname' class='cbitem' value='$sid' id='cb_$sid' /></td>";
			}else{
				$retval .= "<td>Paid</td>";
			}
			$retval .= "<td><label for='cb_$sid'>$date</label></td>";
			$retval .= "<td><label for='cb_$sid'>$itemname</label></td>";
			$retval .= "<td class='number'><label for='cb_$sid'>$unitcost</label></td>";
			$retval .= "<td class='number'><label for='cb_$sid'>$qty</label></td>";
			$retval .= "<td class='number'><label for='cb_$sid'>" . number_format($unitcost * $qty,2) ."</label></td>";
			$retval .= "</tr>";
			$oldcateg = $catname;
			$total += $unitcost * $qty;
			$grandtotal += $unitcost * $qty;
			$laststatus = $status;
		}
		$retval.="<tr><td class='number hdr' colspan=5>Sub-total:</td><td class='number hdr'>". number_format($total,2) ."</td></tr>";
		//$retval .= "<tr><td colspan=7 >&nbsp;</td></tr>";
	}
	}

	if($showpayment==1 and trim($retval)!="") {
		$retval.="<tr><td class='number hdr' colspan=5><span class='grandtotal'>Please Pay This Amount:</span></td><td class='number hdr'><span class='grandtotal'>". number_format($grandtotal,2) ."</span></td></tr>";
		$retval.="<tr><td colspan=6>";
		$retval.="<input type='hidden' name='new_amountdue' id='new_amountdue' value='$grandtotal' /> ";
		$retval.=displaypaymentpad($grandtotal);
		$retval.="</td></tr>";
	}
	return $retval;
}

function getcategoryfromitem($cat, $item) {
	if($cat==1) {
		$sql = " select sas_cat_id from sales_and_services where sas_id='$item' ";
	}elseif($cat==4){
		$sql = " select food_category_id from fnb where fnb_id='$item' ";
	}
	$res = mysql_query($sql);
	list($cid)=mysql_fetch_row($res);
	return $cid;
}

function getitemfromcat($cat="", $itemid="") {
	if($cat == 1) { //extract from sas
		$sql = " select sas_description from sales_and_services where sas_id='$itemid' ";
	}elseif($cat==4){
		$sql = " select fnb_name from fnb where fnb_id='$itemid' ";
	}
	$res = mysql_query($sql);
	if(mysql_num_rows($res)) {
		list($name) =mysql_fetch_row($res);
		return $name;
	}else{
		return '';
	}
}

/**
*
* display part
*/
function getfoodcategories($name="",$selected="",$onchange="") {
	$sql  = "select food_category_id, food_category_name from food_categories order by food_category_name";
	$res = mysql_query($sql);

	while(list($fid, $fname)=mysql_fetch_row($res)) {
		$retval.="<option value='f_$fid' alt='fnb' ";
		$retval.= ($fid==$selected) ? " selected " : "";
		$retval.= ">$fname</option>";
	}

	return $retval;
}

function getfooditems($name="",$selected="",$onchange="") {
	$sql = " select food_categories.food_category_id, food_categories.food_category_name, 
			fnb.fnb_id, fnb.fnb_code, fnb.fnb_name, fnb.fnb_price
			from fnb left join food_categories on fnb.food_category_id=food_categories.food_category_id
			order by food_categories.food_category_name, fnb_name
			";
	$res = mysql_query($sql) or die($sql);

	$retval="<select name='$name' id='$name' ";
	$retval.= ">";
	$retval.="<option></option>";
	$oldcateg='';
	while(list($fcid, $fcname,$fnbid,$fnbcode,$fnbname,$fnbprice)=mysql_fetch_row($res)) {
		if($oldcateg != $fcid) {
			$retval.= ($oldcateg=="")  ? "" : "</optgroup>";
			$retval.="<optgroup label='$fcname' id='fcat_f_$fcid' class='foodopts'>\n";
		}
		$retval.="<option value='$fnbid' alt='$fnbprice' ";
		$retval.= ($fnbid==$selected) ? " selected " : "";
		$retval.= ">$fnbcode - $fnbname</option>\n";
		$oldcateg=$fcid;
	}
	$retval.="</optgroup>";
	$retval.="</select>";
	return $retval;
}

function getsascategories($name="",$selected="",$onchange="") {
	$sql  = "select * from sas_category where sas_cat_id <> 3 order by sas_cat_name";
	$res = mysql_query($sql);

	$retval="";
	while(list($fid, $fname)=mysql_fetch_row($res)) {
		$retval.="<option value='m_$fid'  alt='misc' ";
		$retval.= ($fid==$selected) ? " selected " : "";
		$retval.= ">$fname</option>";
	}

	return $retval;
}

function getsasitems($name="",$selected="",$onchange="") {
	$sql = " select sas_category.sas_cat_id, sas_category.sas_cat_name, 
			sales_and_services.sas_id, sales_and_services.sas_description, sales_and_services.sas_amount
			from sales_and_services left join sas_category on sales_and_services.sas_cat_id=sas_category.sas_cat_id
			where sas_category.sas_cat_id <> 3 order by sas_category.sas_cat_name, sales_and_services.sas_description ;
			";
	$res =mysql_query($sql) or die($sql. mysql_error());

	$retval="<select name='$name' id='$name' ";
	$retval.= ">";
	$retval.="<option></option>";
	$oldcateg='';
	while(list($fcid, $fcname,$fnbid,$fnbname,$fnbprice)=mysql_fetch_row($res)) {
		if($oldcateg != $fcid) {
			$retval.= ($oldcateg=="")  ? "" : "</optgroup>";
			$retval.="<optgroup label='$fcname' id='mcat_m_$fcid' class='foodopts'>\n";
		}
		$retval.="<option value='$fnbid'  alt='$fnbprice' ";
		$retval.= ($fnbid==$selected) ? " selected " : "";
		$retval.= ">$fnbname</option>\n";
		$oldcateg=$fcid;
	}
	$retval.="</optgroup>";
	$retval.="</select>";
	return $retval;
}

function getorderslips($occupancy,$lobbyid) {
	$sql= "select distinct order_code, status,update_date from fnb_sales where occupancy_id=$occupancy and order_code > 0 and status <> 'Cancelled'
			union  select distinct order_code, status,update_date from  room_sales where occupancy_id=$occupancy  and order_code > 0 and status <> 'Cancelled'";
	$sql= "select distinct order_code, status from fnb_sales where occupancy_id=$occupancy and order_code > 0 and status <> 'Cancelled'
			union  select distinct order_code, status from  room_sales where occupancy_id=$occupancy  and order_code > 0 and status <> 'Cancelled'";
	
	
	$res = mysql_query($sql) or die(mysql_error() . $sql);
	//$ret = "<ul id='oclinks'>";
	//$ret = "<button class='oclinks'>";
	while(list($oc, $stat,$update)=mysql_fetch_row($res)) {
		$statdesc="";
		if($stat=="Draft") {
			$statdesc = "For Printing";	
			$statu = 0;
		}elseif($stat=="Printed"){
			$statdesc = "For Payment";
			$statu = 1;
		}elseif($stat=="Paid"){
			$statdesc = "For Viewing";
			$statu = 2;
		}
		//$ret .= "<li><a href='$oc' class='oclinks' alt='$statu'>$oc</a> - $statdesc</li>";
		
		if($lobbyid!="")
		{
			$_sql = "select `datetime` from `shift-transactions` where shift = 'start' order by `datetime` desc limit 0,1";
			$_res = mysql_query($_sql);
			
			list($_sdt)=mysql_fetch_row($_res);			
			if($update>$_sdt||$stat!="Paid"){$ret .= "<button class='oclinks $stat' alt='$statu'>$oc</button>";}
			
		}
		else
		{						
			$ret .= "<button class='oclinks $stat' alt='$statu'>$oc</button>";
		}		
		
	}
	//$ret .= "</ul>";

	
	return $ret;
}

function dropcounter($name, $selected) {
	$retval ="<select name='$name' id='$name'>";
	for($x=0; $x <=20; $x++) {
		$retval.="<option value='$x'>$x</option>";
	}
	$retval.="</select>";
	return $retval;
}

$fooditems = getfooditems("newfooditem");
$sasitems = getsasitems("newsasitem");
$existing = gettransactions($occupancy) ;
$counter = dropcounter('newqty',0);

$_sql = "select settings_value from settings where id = '3'";
$_res = mysql_query($_sql);
list($val)=mysql_fetch_row($_res);
if($val == $occupancy){ $oclinks = getorderslips($occupancy,$occupancy);}
else {$oclinks =getorderslips($occupancy,"");}
//$existing .= gettransactions(4, $occupancy) ;
?>
<style>
#newsascateg,#newfooditem,#newsasitem,#dummy,#newqty {
	height:24px;
	font-size:1em;
	color:#0000ff;
	background-color:#eeeeee;
	font-weight:bold;
	width:240px;
}

.draft {background-color:#FF9900;padding:2px;margin:2px;}
.paid {background-color:#99FF99;padding:2px;margin:2px;}
.printed {background-color:#0099FF;padding:2px;margin:2px;}

.orderset legend {
	border:1px solid #cccccc;
	background-color:#eeeeee;
	color:#ff6600;
	font-weight:bold;
	font-family:verdana, arial, helvetica;
	font-size:.6em;
	padding:2 4 2 4;
}

#orderslist {
	font-family:verdana,arial,helvetica;
	font-size:.7em;
	border-collapse:collapse
}

#orderslist td.hdr {
	font-size: 1em;
	font-weight:bold;
	border-bottom:1px solid #eeeeee;
	text-align:left;
	background-color:#FFFFCC;
	color:#990033;
	padding:4px;
	font-size:.8em;
}
.grandtotal {
	font-size:11px;
	color:#FF3366;
}

#orderslist td {
	border-bottom:1px dotted #cccccc;
	padding:2px;
	font-size:.8em;
}

#orderslist td.number {
	border-bottom:1px dotted #cccccc;
	text-align:right;
	padding:2px;
}

#orderslist td.subhdr {
	font-weight: bold;
	border-bottom: 1px solid #43b7c4;
}

#orderslist td.hdr-heading {
	font-weight: bold;
	color:#339933;
}

#cmdmenu {
	list-style:none;
	margin-left:-40px;
}

#cmdmenu li{
	float:left;
	width:80px;
}

.cmdbtn {
	width:75px;
	border:1px solid  #ffffff;
	background-color: #9BD1E6;
	margin-right:2px;
	padding:2px;
	cursor:pointer;
	font-size:.7em;
}

.oclinks 
{
	width:220px;
	border:1px solid #ffffff;
	margin:2px;
	cursor:pointer;
	color:#000000;
}



#oclinks {
	list-style:none;
	margin-left:-36px;
}

#oclinks li {
	font-size:.7em;
	border:1px solid #ccffcc;
	background-color:#FFCC99;
	margin:2px;
	padding:2px;
	padding-left:4px;
	font-family:lucida,arial,helvetica;
}

#oclinks li a {
	text-decoration:none;
	width:100%;
	color:#CC0033;
}

#oclinks li a:hover {
	color:#006633;
}

.money {
	text-align:right;
}
.tender {
	background-color:#C5FEE9;
}
#newchange{background-color:#ffffff;}
</style>
<div>
<form method="post" action=""  id="myform">
<table width="600">
<tr>
<td width="300" valign="top">
<fieldset class="orderset">
<legend>Select Order Items Here</legend>
<table cellpadding="1" cellspacing="1" border="0">
<tbody>
<tr>
<td>
<select id="newsascateg"  name="newsascateg">
<option value="0">Select category...</option>
	<optgroup label="Miscellaneous">
		<?=getsascategories('mymiscateg')?>
	</optgroup>
	<!--option value="2">Cooperative</option-->
	<optgroup label="Food and Services">
		<?= getfoodcategories("myfoodcateg");?>
	</optgroup>
</select>
</td>
</tr><tr>
<td>
<select id="dummy"></select>
<?= $fooditems . $sasitems?></td>
</tr>
<tr>
<td>
<br /><br />
Remarks: <input type='text' name='newremarks' id="newremarks" />
</td>
</tr>
<tr>
<td>
<span style="font-size:.7em;font-family:lucida,arial,helvetica">No. Items: </span><input type="text" name="qty" id="qty" value="1" size="2" maxlength="2" />
<input type="button"  name="add"  value="Add"  id="add"  class="cmdbtn1" />
</td>
</tr>
</tbody>
</table>
</fieldset>
<br />
<fieldset class="orderset">
<legend>Order Slips</legend>
<input type="button" value="New" id="neworderslip" class="cmdbtn1" />
<?=$oclinks?>
<br /><br />
<div style='font-size:.7em;padding:4px;border:1px solid #cccccc;'>
<span class='draft'>Draft</span>
<span class='printed'>Printed</span>
<span class='Paid'>Paid</span>
</div>
</fieldset>
</td>

<td  valign="top">
<span style="font-size:.7em;font-family:lucida,arial,helvetica;">
Order Slip #:<input type="text" name="order_code" id="order_code" value="<?=$order_code?>" />
</span>

<ul id="cmdmenu">
<li><input type="button" name="cmdbtn" id="cmdPrint" value="Print"  class='cmdbtn' /></li>
<li><input type="button" name="cmdbtn" id="cmdRemove" value="Remove"  class='cmdbtn' /></li>
<li><input type="button" name="cmdbtn" id="cmdCancel" value="Cancel"  class='cmdbtn' /></li>
<li><input type="button" name="cmdbtn" id="cmdPay" value="Pay"  class='cmdbtn' /></li>
<li><input type="button" name="cmdbtn" id="cmdReprint" value="RePrint"  class='cmdbtn' /></li>
<li><input type="button" name="cmdbtn" id="cmdDiscount" value="Discount"  class='cmdbtn' /></li>
</ul>

<div style="clear:both;"></div>

<table id="orderslist"  width="360" cellpadding="1" cellspacing="1" border="0">
<tbody>
</tbody>
</table>
<input type="hidden" id="newunitprice" name="newunitprice" />
<input type="hidden" id="occupancy" name="occupancy" value="<?=$occupancy?>" />
<input type="hidden" id="roomid" name="roomid" value="<?=$room?>" />
<?php include_once("paymentpad.php") ?>
</tr>
</table>



</form>
</div>
<link rel="stylesheet" type="text/css" href="../css/ajaxphp.css" />
<link rel="stylesheet" type="text/css" href="../css/jquery.keypad.css" />
<script src="../js/jquery.js" type="text/javascript"></script>
<script src="../js/jquery.keypad.pack.js" type="text/javascript"></script>
<script lang="javascript">
	function recompute(){
		var tender = $("#newcash").val()*1 + $("#newcard").val()*1;
		$("#newchange").val(  tender - $("#new_amountdue").val());
	}

	var focusme="newcash";
	$(document).ready(function(){
		$("#newremarks").keypad({keypadOnly: false, 
    layout: $.keypad.qwertyLayout});
		$("#qty").keypad();
		$("#newsasitem").hide();
		$("#newfooditem").hide();
		$(".cmdbtn").hide();
		$("#newfooditem").change(function() {
			$("#newunitprice").val($("#newfooditem option:selected").attr('alt') );
		});
		$("#newsasitem").change(function() {
			$("#newunitprice").val($("#newsasitem option:selected").attr('alt') );
		});
		
		$("#newsascateg").change(function(){
			var alt = $("#newsascateg option:selected").attr('alt');
			$("#newsasitem").hide();
			$("#newfooditem").hide();
			$("#dummy").hide();
			if(alt=='fnb') {
				$("#newfooditem").show();
				$(".foodopts").hide();
				$("#fcat_" + $(this).val()).show(); 
			}else if(alt=='misc') {
				$("#newsasitem").show();
				$(".foodopts").hide();
				$("#mcat_" + $(this).val()).show(); 
				//$("#mcat_" + $(this).val() + " option:first").attr("selected","selected"); 
			}else{
				$("#dummy").show();
			}	
			
			
		});
		$("#add").click(function(){
			if($("#order_code").val()=="") {
				$("#order_code").val(new Date().getTime());
			}
			$("#cmdPrint").show();
			$("#cmdRemove").show();
			$("#cmdDiscount").show();
			$.post("order.php",{ act:'add',showpayment:0, occupancy: <?=$occupancy?>, data: $("#myform").serialize() }, function(resp) {
				$("#orderslist tbody").html(resp);
				
			});
			return false;
		});
		$(".oclinks").click(function(){
			$("#add").hide();
			var sp = 0;
			if($(this).attr("alt")==0) 
			{
				$("#cmdPrint").show();
				$("#cmdRemove").show();
				$("#cmdCancel").hide();
				$("#cmdPay").hide();
				$("#cmdReprint").hide();
				$("#cmdDiscount").show();
				sp = 0;
			}
			else if($(this).attr("alt")==1)
			{
				$("#cmdPrint").hide();
				$("#cmdRemove").hide();
				$("#cmdCancel").show();
				$("#cmdPay").show();
				$("#cmdReprint").show();
				$("#cmdDiscount").show();
				sp = 1;
			}
			else if($(this).attr("alt")==2)
			{
				$("#cmdPrint").hide();
				$("#cmdRemove").hide();
				$("#cmdCancel").hide();
				$("#cmdPay").hide();
				$("#cmdReprint").hide();
				$("#cmdDiscount").hide();
				sp =0;
			}
			
			$("#order_code").val($(this).html());
			$.post("order.php",{ act:'viewoc',showpayment:sp, occupancy: <?=$occupancy?>, order_code: $(this).html(), roomid:$("#roomid").val() }, function(resp) {
				$("#carddetails").hide();
				$("#orderslist tbody").html(resp);

				$("#newcard").change(function(){
					if($(this).val()==0) 
					$("#carddetails").hide();
					else $("#carddetails").show();
				});
				$(".tender").click(function(){
					$(".tender").removeClass("hilite");
					focusme = $(this).attr("id");
					$(this).addClass("hilite");
				});
				$(".denomination").click(function() {
					if($(this).val()=="Clear") {
						$("#" + focusme).val( 0);	
					}else{
						var curval = $("#" + focusme).val() * 1;
						var newval = $(this).val() * 1;
						$("#" + focusme).val( curval + newval);
					}
					if($("#newcard").val()==0) $("#carddetails").hide();
					else $("#carddetails").show();
					recompute();
				});
			});
			return false;
		});
		$(".cmdbtn").click(function(){
			var sp=0;			
			if($(this).val()=="Print" || $(this).val()=="RePrint") {
				$(".cbitem").attr("checked",true);
				$("#cmdPrint").hide();
				$("#cmdRemove").hide();
				$("#cmdCancel").show();
				$("#cmdPay").show();
				$("#cmdReprint").show();
				$("#cmdDiscount").show();
				$("#add").hide();
				sp=1;
			}
			else if($(this).val()=="Cancel") {

			}
			else if($(this).val()=="Pay") {
				$("#cmdPrint").hide();
				$("#cmdRemove").hide();
				$("#cmdCancel").hide();
				$("#cmdPay").hide();
				$("#cmdReprint").hide();
				$("#cmdDiscount").hide();
			}
			else if($(this).val()=="Discount") {
				document.location.href='fooddiscount.php?code=' + $("#order_code").val() + '&total=' + $("#new_amountdue").val() +'&roomid='+$("#roomid").val()+'&occupancy='+$("#occupancy").val();
			}
			$.post("order.php",{ act:'cmd',showpayment:sp, newstatus: $(this).val(),occupancy: <?=$occupancy?>,data: $("#myform").serialize() }, function(resp) {
				$("#orderslist tbody").html(resp);
				if(sp==1) {
					$("#carddetails").hide();

					$("#newcard").change(function(){
						if($(this).val()==0) 
						$("#carddetails").hide();
						else $("#carddetails").show();
					});
					$(".tender").click(function(){
						$(".tender").removeClass("hilite");
						focusme = $(this).attr("id");
						$(this).addClass("hilite");
					});
					$(".denomination").click(function() {
						if($(this).val()=="Clear") {
							$("#" + focusme).val( 0);	
						}else{
							var curval = $("#" + focusme).val() * 1;
							var newval = $(this).val() * 1;
							$("#" + focusme).val( curval + newval);
						}
						if($("#newcard").val()==0) $("#carddetails").hide();
						else $("#carddetails").show();
						recompute();
					});
				}
			});
			return false;
		});

		$("#neworderslip").click(function(){
			$("#add").show();
			$("#cmdPrint").show();
			$("#cmdRemove").show();
			$("#cmdCancel").hide();
			$("#cmdDiscount").show();
			$("#cmdPay").hide();
			$("#cmdReprint").hide();
			$("#orderslist tbody").html("");
			$("#order_code").val(new Date().getTime());
		});

	})
</script>